package com.example.wzsdk.scan;

import android.content.Context;

import com.example.wzsdk.callback.SearchFinish;
import com.example.wzsdk.callback.onSearchFinsh;
import com.example.wzsdk.tools.ToolsClass;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by SunLight on 2017/8/11.
 */

public class Search implements onSearchFinsh {
    private static final String WZONE_IP = "192.168.";
    private static final int MAX_NETWORK_SEGMENT = 255;
    private String AppId = null;
    private Context context = null;
    private List<ScanSaveEigenValue> scanSaveEigenValueList;
    private SearchFinish searchFish;
    private List<String[]> Wifi = new ArrayList<>();

    public Search(String AppId, Context context) {
        this.AppId = AppId;
        this.context = context;
        scanSaveEigenValueList = new ArrayList<>();
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:27
     * @Method 设置监听
     **/
    public void setSearchListener(SearchFinish searchFish) {
        this.searchFish = searchFish;
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:27
     * @Method 搜索局域网主机（该方法在适用于无线网络环境）
     **/
    public void StartSearchToWifi() {
        Wifi.clear();
        scanSaveEigenValueList.clear();
        for (int i = 0; i < MAX_NETWORK_SEGMENT; i++) {
            new ScanThread(ToolsClass.getLocalHostIP(context) + "." + i, i, scanSaveEigenValueList, this, AppId).start();
        }
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:27
     * @Method 搜索局域网主机（该方法在适用于有线网络环境）
     **/
    public void StartSearchToNetWork(String index) {
        Wifi.clear();
        scanSaveEigenValueList.clear();
        for (int i = 0; i < MAX_NETWORK_SEGMENT; i++) {
            new ScanThread(WZONE_IP + index + "." + i, i, scanSaveEigenValueList, this, AppId).start();
        }
    }

    /**
     * @User SunLight
     * @Data 2018/1/11 16:28
     * @Method 搜索回调方法（搜索完毕后回调该方法）
     **/
    @Override
    public void onFinsh() {
        for (int i = 0; i < scanSaveEigenValueList.size(); i++) {
            Wifi.add(new String[]{scanSaveEigenValueList.get(i).getSocket().getInetAddress().toString().substring(1, scanSaveEigenValueList.get(i).getSocket().getInetAddress().toString().length()), ToolsClass.Dut_ID(scanSaveEigenValueList.get(i).getSnHash(), 10), String.valueOf(ToolsClass.SecretKey(scanSaveEigenValueList.get(i).getHosttype()))});
            try {
                scanSaveEigenValueList.get(i).getSocket().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        searchFish.onSearchFinsh(Wifi);
    }


}
